<template>
  <img 
    :src="currentSrc" 
    :alt="alt"
    :class="imgClass"
    :style="imgStyle"
    @error="handleError"
    @load="handleSuccess"
    ref="img"
  />
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import { checkImageAccessibility } from '@/assets/js/image-helper';

export default {
  name: 'ImageLoader',
  props: {
    src: {
      type: String,
      required: true
    },
    alt: {
      type: String,
      default: '图片'
    },
    imgClass: {
      type: String,
      default: ''
    },
    imgStyle: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    // 当前显示的src
    const currentSrc = ref('');
    const img = ref(null);
    const loading = ref(true);
    const error = ref(false);
    
    // 加载图片的方法
    const loadImage = async (src) => {
      if (!src) return;
      
      loading.value = true;
      error.value = false;
      
      console.log('尝试加载图片:', src);
      
      try {
        // 尝试多种URL格式，直到找到可用的
        const accessibleUrl = await checkImageAccessibility(src);
        currentSrc.value = accessibleUrl;
        loading.value = false;
      } catch (err) {
        console.error('所有图片URL尝试失败:', err);
        currentSrc.value = '/images/placeholder.png';
        error.value = true;
        loading.value = false;
      }
    };
    
    // 错误处理
    const handleError = () => {
      console.error('图片加载失败:', currentSrc.value);
      // 如果当前不是占位图，则设置占位图
      if (!currentSrc.value.includes('placeholder.png')) {
        currentSrc.value = '/images/placeholder.png';
      }
      error.value = true;
      loading.value = false;
    };
    
    // 成功处理
    const handleSuccess = () => {
      console.log('图片加载成功:', currentSrc.value);
      loading.value = false;
      error.value = false;
    };
    
    // 监听src变化
    watch(() => props.src, (newSrc) => {
      if (newSrc !== currentSrc.value) {
        loadImage(newSrc);
      }
    });
    
    // 组件挂载时加载图片
    onMounted(() => {
      loadImage(props.src);
    });
    
    return {
      currentSrc,
      img,
      loading,
      error,
      handleError,
      handleSuccess
    };
  }
};
</script>

<style scoped>
/* 可以添加自定义样式，比如加载中的动画等 */
</style> 